import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf

with tf.compat.v1.Session() as sess:
    a = tf.constant(1)
    print(sess.run(a))  # 1

    a = tf.zeros(shape=[2, 3], dtype=tf.float32)
    print(a.eval())  # [2, 3]型的0（浮点型）矩阵

    b = tf.ones(shape=[2, 3], dtype=tf.int32)
    print(b.eval())  # [2, 3]型的1（整形）矩阵

    # 类型转换
    c = tf.cast(b, dtype=tf.float32)
    print(c.eval())  # [2, 3] 型的1（浮点型）矩阵

    # 形状改变--静态形状, 只能在同样的阶数下对未知维度进行改变，固定后不能改变
    a_p = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, None])
    b_p = tf.compat.v1.placeholder(dtype=tf.float32, shape=[None, 2])  # 哪个维度确定后就不能更改
    c_p = tf.compat.v1.placeholder(dtype=tf.float32, shape=[2, 3])

    print("a_p shape:", a_p.shape)  # a_p shape: (?, ?)
    print("b_p shape:", b_p.shape)  # b_p shape: (?, 2)
    print("c_p shape:", c_p.shape)  # c_p shape: (2, 3)

    a_p.set_shape(shape=[3, 4])  # 此时a_p的阶数固定，不能再静态修改此形状
    print("a_p shape:", a_p.shape)  # a_p shape: (3, 4)
    b_p.set_shape(shape=[10, 2])  # 此时b_p的阶数固定，不能再静态修改此形状
    print("b_p shape:", b_p.shape)  # b_p shape: (10, 2)

    # 形状改变--动态形状， 可以对阶数进行改变，但是必须保证元素数量相同
    new_b_p = tf.reshape(b_p, shape=[2, -1, 1])
    print("new_b_p shape:", new_b_p.shape)  # new_b_p shape: (2, 10, 1)

    # 创建随机值张量
    r = tf.random.normal(shape=[3, 1], mean=0, stddev=1)
    print("r = \n", r.eval())
    print("r shape:", r.shape)  # r shape: (3, 1)
